package com.sangeng.service.impl;

import com.sangeng.domain.LoginUser;
import com.sangeng.domain.ResponseResult;
import com.sangeng.domain.User;
import com.sangeng.service.LoginService;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import io.jsonwebtoken.Jwt;
import jdk.jfr.internal.EventWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LENOVO
 * @version 1.0
 * @date 2025/6/17 15:45
 */
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    /**
     * 登录
     * @param user  用户
     *
     * 这里模拟了UsernamePasswordAuthenticationFilter过滤器的逻辑,因为这个过滤器在本项目失去意义
     *
     * @return ResponseResult
     */
    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager authenticate进行用户认证
        //需要把用户名和密码封装进Authentication对象  UsernamePasswordAuthenticationToken是Authentication的实现类
        //参数一为用户名，参数二为密码
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        //使用authenticationManager的authenticate方法进行认证
        //也就是去到我们自定义的UserDetailsServiceImpl中的loadUserByUsername方法进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没通过，给出对应的提示
        if (authenticate == null){
            throw new RuntimeException("登陆失败");
        }

        //如果认证通过，使用userid生成一个jwt  jwt存入ResponseResult返回给前端
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUser().getId().toString());
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);

        //把完整的用户信息存入redis   userid 作为key
        redisCache.setCacheObject("login:"+loginUser.getUser().getId(),loginUser);//虽然这里loginUser存入的redis,但实际上权限字段并没有存进去,具体看loginUser实体类的注释


        return new ResponseResult(200,"登录成功",map);
    }

    /**
     * 退出登录
     * @return ResponseResult
     */
    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        Long userId = loginUser.getUser().getId();
        //根据用户id删除redis中的用户数据
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"退出成功");
    }
}